package sunyu.toolkit.core;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * XML工具类
 *
 * @author 孙宇
 */
public class XmlKit {

    private static final ObjectMapper xmlMapper = new XmlMapper();

    static {
        xmlMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);//允许json字符串属性没有双引号
        xmlMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);//允许json字符串属性是单引号包裹
        xmlMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));//设置日期格式
        xmlMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);//属性为""或者为NULL都不进行序列化
    }

    public static String toXml(Object obj) {
        try {
            return xmlMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            System.out.println(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public static <T> T toObject(String xml,
                                 Class<T> clazz) {
        try {
            return xmlMapper.readValue(xml, clazz);
        } catch (IOException e) {
            System.out.println(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }


}
